<?php
/**
 * @file func_seo.php 两个函数，一个去除多余的a标签，一个给文章加上头尾
 * @package Rewrite
 * @subpackage 
 * @version $id: 0.1 UTF-8 2009-3-3 下午01:52:16 $
 * @author LD King (mifunny.info)
 * @copyright Copyright (c) 2007 - 2009 MiFunny China Inc. (http://mifunny.info)
 * 补充知识: PHP整数除法 
 * round() 四捨五入		4.5 -> 5		4.4 -> 4
 * floor() 無條件捨去		4.5 -> 4		4.4 -> 4
 * ceil() 無條件進位		4.5 -> 5		4.4 -> 5
 */

/**
 * 切除多余的a标签
 *
 * @param String $article
 * @param String $key
 * @return String $new
 */
function strip_a_tag($article, 	$key = '81oscar.info') {
/*	$new = preg_replace('/(<a.*?href.+?'.$key.'.+?>.+?<\/a>)|<a.*?href.+?>(.*?)<\/a>/i', "$1$2", $article);
	*/
	$new = preg_replace('/<a.*?href.+?>(.*?)<\/a>/i', "$1", $article);
	
	return $new;
} //END func strip_a_tag


/**
 * 给文章加上首尾(150字)
 * 	头: --><p class="post-excerpt"> ... </p>
 *  尾: <p class="post-quote"> ... </p>
 *
 * @param String $article
 * @param Array $tags
 * @return String
 */
function add_tail($article, $tags=array()) {
	$top = '';
	$bottom = '';
	$noHTML = strip_tags($article);
	$len = utf8_strlen($noHTML);
	
	if ($len < 300) {
		$top = substr($noHTML, floor($len/2), $len-1);
		$bottom = substr($noHTML, 0, floor($len/2));
		
	}else {
		$top = substr($noHTML, $len-210 , $len-51);
		$bottom = substr($noHTML, 51, 210);
	}
	$top = utf8_trim($top);
	$bottom = utf8_trim($bottom);

	/* 加入关键字 */
	foreach ($tags as $k => $v) {
		$top .= ', '.$v;
	}
	
	$top = '<p class="post-excerpt">'.$top.' '.sha1($top).' ...</p>';
	$bottom = '<p class="post-quote">'.sha1($bottom).' '.$bottom.' ...</p>'; 
	$new = $top.$article.$bottom;
	return $new;
} //END func add_tail


/**
 * 去除首位空白,乱码
 * 以下函数来自Wordpress中文工具箱 
 * http://yanfeng.org/blog/wordpress/kit
 *
 * @param String $str
 * @return String
 */
function utf8_trim($str) {
//	$len = strlen($str);
	for ($i=strlen($str)-1; $i>=0; $i-=1){
		$hex .= ' '.ord($str[$i]);
		$ch = ord($str[$i]);
        if (($ch & 128)==0) return(substr($str,0,$i));
		if (($ch & 192)==192) return(substr($str,0,$i));
	}
	return($str.$hex);
} //END func utf8_trim

/**
 * 说明：计算 UTF-8 字符串长度（忽略字节的方案）
 * 整理：http://www.CodeBit.cn 
 *
 * @param String $str
 * @return int
 */
function utf8_strlen($str) {
	$i = 0;
	$count = 0;
	$len = strlen ($str);
	while ($i < $len){
		$chr = ord ($str[$i]);
		$count++;
		$i++;
		if($i >= $len) break;
		if($chr & 0x80) {
			$chr <<= 1;
			while ($chr & 0x80) {
				$i++;
				$chr <<= 1;
			}
		}
	}
	return $count;
} //END func utf8_strlen
?>